const ffmpeg = require('fluent-ffmpeg');
const fs = require('fs');
const path = require('path');

// 视频文件夹路径
const videoFolder = './video';
// 输出总文件夹路径
const outputBaseFolder = './output';

// 确保输出总文件夹存在
if (!fs.existsSync(outputBaseFolder)) {
    fs.mkdirSync(outputBaseFolder);
}

// 读取视频文件夹
fs.readdir(videoFolder, (err, files) => {
    if (err) {
        console.error('读取视频文件夹时出错:', err);
        return;
    }

    // 过滤出 MP4 视频文件
    const videoFiles = files.filter(file => path.extname(file).toLowerCase() === '.mp4');

    // 处理每个视频文件
    videoFiles.forEach((videoFile) => {
        const videoPath = path.join(videoFolder, videoFile);
        const videoName = path.parse(videoFile).name;
        const videoOutputFolder = path.join(outputBaseFolder, videoName);

        // 创建视频对应的输出子文件夹
        if (!fs.existsSync(videoOutputFolder)) {
            fs.mkdirSync(videoOutputFolder);
        }

        ffmpeg.ffprobe(videoPath, (err, metadata) => {
            if (err) {
                console.error(`获取 ${videoFile} 元数据时出错:`, err);
                return;
            }
            const duration = metadata.format.duration;

            for (let currentTime = 1; currentTime < duration; currentTime++) {
                const outputPath = path.join(videoOutputFolder, `${videoName}_${currentTime}s_frame.jpg`);

                ffmpeg(videoPath)
                   .seekInput(currentTime) // 指定抽取时间（秒）
                   .frames(1) // 抽取一帧
                   .save(outputPath)
                   .on('end', () => {
                        console.log(`成功抽取 ${videoFile} 第 ${currentTime} 秒的帧，保存为 ${outputPath}`);
                    })
                   .on('error', (err) => {
                        console.error(`处理 ${videoFile} 第 ${currentTime} 秒时出错:`, err);
                    });
            }
        });
    });
});